package com.caird.pmp.iot.handler;


import com.caird.common.utils.DataTypeUtils;
import com.caird.pmp.iot.cache.SimNoListCache;
import com.caird.pmp.iot.entity.DeviceShadow;
import com.caird.pmp.iot.server.BbChannelManager;
import com.caird.pmp.iot.service.CacheService;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Date;


@Slf4j
public abstract class HandlerBase implements IHandler {
    @Autowired
    protected BbChannelManager bbChannelManager;

    @Autowired
    protected CacheService cacheService;

    @Autowired
    protected RedisTemplate redisTemplate;

    /**
     * 判断登录
     */
    public boolean isLogin(Channel channel) {
        return bbChannelManager.isLogin(channel);
    }

    /**
     * 登入
     */
    public boolean login(Channel channel, String simNo) {
        if (!bbChannelManager.isLogin(channel)) {
            log.info("设备登入：" + simNo);
            bbChannelManager.login(channel, simNo);
            redisTemplate.opsForHash().put("pmp-onlines", simNo, true);
            DeviceShadow shadow = getShadow(simNo);
            shadow.setIsOnline(true);
            shadow.setOnlineTime(new Date());
            setShadow(simNo, shadow);
            channel.closeFuture().addListener(channelFutureListener);
        }
        return true;
    }


    /**
     * 登出
     */
    public boolean logout(Channel channel) {
        if (bbChannelManager.isLogin(channel)) {
            String simNo = BbChannelManager.getLoginId(channel);
            log.info("设备登出：" + simNo);
            bbChannelManager.logout(channel);
            redisTemplate.opsForHash().delete("pmp-onlines", simNo);
            DeviceShadow shadow = getShadow(simNo);
            shadow.setIsOnline(false);
            shadow.setOfflineTime(new Date());
            setShadow(simNo, shadow);
        }
        return true;
    }

    /**
     * 失效登出
     */
    private ChannelFutureListener channelFutureListener = future -> {
        logout(future.channel());
    };

    /**
     * 获取设备影子
     */
    public DeviceShadow getShadow(String simNo) {
        DeviceShadow shadow = (DeviceShadow)redisTemplate.opsForHash().get("pmp-devices", simNo);
        if (null == shadow)
            shadow = new DeviceShadow();
        return shadow;
    }

    /**
     * 设置设备影子
     */
    public void setShadow(String simNo, DeviceShadow shadow) {
        shadow.setTime(new Date());
        redisTemplate.opsForHash().put("pmp-devices", simNo, shadow);
    }

    /**发送数据*/
    public void writeAndFlush(Channel channel, ByteBuf byteBuf) {
        log.info("发送：" + DataTypeUtils.byteBuf2HexString(byteBuf.resetReaderIndex()));
        channel.writeAndFlush(byteBuf);
    }


}
